//
//  BankViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/21.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import MJRefresh

class BankViewController: KMViewController {
    
    fileprivate let cellId = "bankCell"
    fileprivate var bankType = businessHall //银行类型
    fileprivate var bankName = bank_title //银行名称
    
    fileprivate var latitude:Double = 0 //经度
    fileprivate var longitude:Double = 0 //纬度
    fileprivate var city = "" //城市
    
    fileprivate var page = 1 //页数
    
    var dataArray = [BankDetailsModel]()
    
    fileprivate let search = AMapSearchAPI()
    fileprivate let locationManager = AMapLocationManager()
    
    var tableView : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = nearbyBank
        
        createSubView()
        getCurrentLocation()

    }
    
    //MARK: 添加子视图
    fileprivate func createSubView() {
        
        let headView = BankHeadView()
        headView.bankDelegate = self
        self.view.addSubview(headView)
        
        headView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.tableFooterView = UIView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(BankDetailsCell.self, forCellReuseIdentifier: cellId)
        headView.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(RATIO_H(maxNum: 60))
        }
        
        headView.bringSubview(toFront: headView.tableView)
        
        let footer = MJRefreshBackNormalFooter.init {[weak self] in
            self?.searchBuild(latitude: (self?.latitude)!, longitude: (self?.longitude)!, city: (self?.city)!)
        }
        tableView.mj_footer = footer
        footer?.activityIndicatorViewStyle = .gray
        footer?.stateLabel.textColor = UIColor.gray
        
        
    }
    
    //MARK: 获取当前位置
    fileprivate func getCurrentLocation() {
        
        KMTool.waiting(searchForNearbyBanks)
        locationManager.desiredAccuracy = kCLLocationAccuracyBest //设置精准度
        locationManager.locationTimeout = 2 //定位超时
        locationManager.reGeocodeTimeout = 2 //逆地址超时
        locationManager.requestLocation(withReGeocode: false) { [weak self](location, reGeocode, error) in
            
            KMTool.stop()
            let code  = (error as NSError?)?.code
            
            if code == AMapLocationErrorCode.locateFailed.rawValue {
                KMTool.showText(_text: (error?.localizedDescription)!)
                return
            }else if code == AMapLocationErrorCode.reGeocodeFailed.rawValue || code == AMapLocationErrorCode.timeOut.rawValue || code == AMapLocationErrorCode.cannotFindHost.rawValue || code == AMapLocationErrorCode.badURL.rawValue || code == AMapLocationErrorCode.notConnectedToInternet.rawValue || code == AMapLocationErrorCode.cannotConnectToHost.rawValue {
                
                KMTool.showText(_text: (error?.localizedDescription)!)
                
            }else{
                
                MyLog(location?.coordinate)
                if location == nil {
                    return
                }
                let geocoder = CLGeocoder()
                geocoder.reverseGeocodeLocation(location!, completionHandler: { (array, error) in
                    if array != nil && (array?.count)! > 0 {
                        let placemark = array?.first
                        //获取城市
                        var city = placemark?.locality
                        if city != nil {
                            MyLog(city)
                            MyLog(placemark?.name)
                            MyLog(placemark?.subLocality)
                            MyLog(placemark?.country)
                            MyLog(placemark?.administrativeArea)
                        }else{
                            city = placemark?.administrativeArea
                            MyLog(city)
                            MyLog(placemark?.name)
                            MyLog(placemark?.subLocality)
                            MyLog(placemark?.country)
                            MyLog(placemark?.administrativeArea)
                        }
                        
                        self?.latitude = (location?.coordinate.latitude)!
                        self?.longitude = (location?.coordinate.longitude)!
                        self?.city = city!
                        self?.searchBuild(latitude: (self?.latitude)!, longitude: (self?.longitude)!, city: (self?.city)!)
                    }
                })
                
            }
            
            
            
        }
    }

    //MARK: 获取指定建筑物
    fileprivate func searchBuild(latitude:Double,longitude:Double,city:String) {
        
        search?.delegate = self
        
        let request = AMapPOIAroundSearchRequest()

        request.offset = 30 //加载的条数
        request.radius = 20000 //搜索范围(m)
        request.page = self.page
        request.keywords = self.bankName
        request.city = city
        request.requireExtension = true
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(latitude), longitude: CGFloat(longitude))
//        let points:[AMapGeoPoint] = [AMapGeoPoint.location(withLatitude: CGFloat(latitude), longitude: CGFloat(longitude)),AMapGeoPoint.location(withLatitude: CGFloat(latitude+1), longitude: CGFloat(longitude+1))]
//        request.polygon = AMapGeoPolygon.init(points: points)
        search?.aMapPOIAroundSearch(request)
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()


    }

}

extension BankViewController : AMapSearchDelegate {

    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {

      
        self.tableView.mj_footer.endRefreshing()
        
        KMTool.showText(_text: searchFail)
       
    }
    
    

    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        
        
        self.tableView.mj_footer.endRefreshing()
    
        
        if response.pois.count == 0 {
            KMTool.showText(_text: notAboutNews)
            if self.page == 1 {
                self.bankName = bank_title
                self.searchBuild(latitude: self.latitude, longitude: self.longitude, city: self.city)
            }
            
            return
        }
        
        var count = 0
        
        for poi in response.pois {
            
            let model = BankDetailsModel()
            model.name = poi.name
            model.address = poi.address
            model.distance = poi.distance
            model.type = poi.type
            model.latitude = poi.location.latitude
            model.longitude = poi.location.longitude
            model.city = poi.city
            model.tel = poi.tel
            
            
            MyLog("\(poi.name ?? ""),\(poi.address ?? ""),\(poi.distance),\(poi.type ?? ""),\(poi.tel ?? "")")
            
            //信息过滤
            if self.bankType != businessHall {
                if (poi.type.contains(automaticTellerMachine) || poi.type.contains("ATM")) && poi.name.contains(bankName) && !poi.name.contains(parkingLot) {
                    self.dataArray.append(model)
                    count += 1
                }
            }else{
                if poi.type.contains(";\(bank_title)") && poi.name.contains(bankName) && !poi.name.contains(parkingLot) {
                    self.dataArray.append(model)
                    count += 1
                }
            }
        }
        
        if count == 0 && self.page == 1 {
            
            self.bankName = bank_title
            self.searchBuild(latitude: self.latitude, longitude: self.longitude, city: self.city)
            return
        }
    
        
        self.page += 1
        self.tableView.reloadData()
        
        if self.page == 2 {
            let indexPath = NSIndexPath.init(row: 0, section: 0)
            self.tableView.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: false)
        }
        
    
    }
    
    
}

extension BankViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 80)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if dataArray.count == 0 {
            return UITableViewCell()
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? BankDetailsCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let bankMapVC = BankMapViewController.init(startLatitude: CGFloat(self.latitude), startLongitude: CGFloat(self.longitude), model:dataArray[indexPath.row])
        self.navigationController?.pushViewController(bankMapVC, animated: true)
    }
}

extension BankViewController : BankHeadViewDelegate {
    
    //MARK: 选择搜索的银行类型
    func selectBank(type: String, name: String) {
        
        if self.bankType == type && self.bankName == name {
            return
        }
        
        self.page = 1
        self.dataArray.removeAll()
        
        self.bankName = name
        self.bankType = type
        
        if self.bankName == allBanks {
            self.bankName = bank_title
        }
        
        //通过经纬度查询建筑
        self.searchBuild(latitude: self.latitude, longitude: self.longitude, city: self.city)
        
    }
    
}
